package com.example.blogslogin_and_register.controller;

import com.example.blogslogin_and_register.Utils.CheckCodeUtil;
import com.example.blogslogin_and_register.domain.UserInfo;
import com.example.blogslogin_and_register.domain.UserResult;
import com.example.blogslogin_and_register.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 用户数据操作---->登录、注册
 *
 * @author 啦啦啦
 */
@RestController
@Slf4j
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/login/{mobile}/{password}")
    public UserResult loginByMobile(@PathVariable("mobile") int mobile, @PathVariable("password") String password) {
        UserInfo info = userService.loginByMobile(new UserInfo(mobile));
        if (info != null) {
            if (password.equals(info.getPassword())) {
                return  new UserResult(info, "登录成功！");
            } else {
                return new UserResult(null, "登录失败！密码错误！");
            }
        } else {
            return new UserResult(null, "登录失败！用户名不存在,请先注册后在登陆！");
        }
    }

    @PostMapping("/register")
    public UserResult register(@RequestBody UserInfo user){
        UserInfo userInfo = userService.loginByMobile(user);
        if (userInfo==null){
            UserInfo register = userService.register(user);
            if (register!=null){
                return new UserResult(register,"注册成功！");
            }else {
                return new UserResult(null,"注册失败！");
            }
        }else {
            return new UserResult(null,"注册失败！该手机用户已存在！");
        }
    }

    @GetMapping("/getCheckCode")
    public String  checkCode() throws IOException {
        FileOutputStream fos  = new FileOutputStream("E:/dev/webserver/nginx-1.21.6/html/checkimg.jpg");
        String checkcode = CheckCodeUtil.outputVerifyImage(100, 50, fos, 4);
        System.out.println(checkcode);
        return checkcode;
    }
}
